/*
 * @Author: Yxliam
 * @Date: 2023-12-12 17:13:51
 * @LastEditors: Yxliam
 * @LastEditTime: 2023-12-15 17:40:28
 * @Description:
 */
import React, {useState, useEffect} from 'react';
// import {HomeOutline} from '@fruits-chain/icons-react-native';
import {TransitionPresets} from '@react-navigation/stack';
import {
  Text,
  View,
  FlatList,
  TouchableOpacity,
  Dimensions,
  Image,
} from 'react-native';
import styles from './styles';
import LinearGradinet from 'react-native-linear-gradient';
import Ionicons from 'react-native-vector-icons/Ionicons';
import {
  PanGestureHandler,
  State,
  GestureHandlerRootView,
} from 'react-native-gesture-handler';
import storage from '../../utils/storage';
import dayjs from 'dayjs';

const WeekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const screenWidth = Dimensions.get('window').width;

type Item = {
  id: string;
  isFinish: boolean;
  time: string;
  title: string;
  content?: string;
};

const MyHome = () => {
  const [dateRange, setDateRange] = useState<any>([]);
  const [selectedDate, setSelectedDate] = useState<any>(null);
  const [gestureState, setGestureState] = useState<any>(State.UNDETERMINED);
  const [offsetX, setOffsetX] = useState<any>(0);

  const [dataSource, setDataSource] = useState<Item[]>([]);

  const Navs = [
    {
      title: '添加待办、备忘',
      tip: '和自己做个约定，提醒自己',
      icon: 'bag-add',
    },
    {
      title: '数据统计',
      tip: '数据记录，一目了然',
      icon: 'stats-chart',
    },
  ];

  useEffect(() => {
    storage.getAllDataForKey('public').then(res => {
      setDataSource(res);
    });
  }, []);

  useEffect(() => {
    // 获取当前日期，并计算出当前周一到周日的日期范围
    const today = dayjs();
    const startDate = today.startOf('week');
    const endDate = today.endOf('week');
    const days = [];

    for (let i = 0; i < 7; i++) {
      const date = startDate.add(i, 'days');
      const dayOfWeek = date.day();
      days.push({
        date: date.format('MM.DD'),
        deteYearMonth: date.format('YYYY.MM'),
        day: WeekDays[dayOfWeek],
      });
    }

    setDateRange(days);
    setSelectedDate(days[0]);
  }, []);

  // 处理手势滑动事件
  const handleGestureEvent = (event: any) => {
    setGestureState(event.nativeEvent.state);
    setOffsetX(event.nativeEvent.translationX);
  };

  // 处理手势结束事件
  const handleGestureEnd = () => {
    if (gestureState === State.END) {
      const threshold = 0.3 * screenWidth; // 滑动超过屏幕宽度的30%才切换日期
      const moveLeft = offsetX < 0;
      let newSelectedDate = selectedDate;

      if (Math.abs(offsetX) > threshold) {
        const nextIndex = moveLeft
          ? dateRange.indexOf(selectedDate) + 1
          : dateRange.indexOf(selectedDate) - 1;
        if (nextIndex >= 0 && nextIndex < dateRange.length) {
          newSelectedDate = dateRange[nextIndex];
        }
      }

      setSelectedDate(newSelectedDate);
      setGestureState(State.UNDETERMINED);
      setOffsetX(0);
    }
  };

  const checkHandle = (key: number) => {
    let target = dataSource[key];
    target.isFinish = !target.isFinish;
    setDataSource([...dataSource]);
  };

  // 渲染日期单元格
  const renderItem = (props: any) => (
    <TouchableOpacity
      style={styles.dateCell}
      onPress={() => setSelectedDate(props.item)}>
      <Text
        style={[
          styles.dateText,
          props.item === selectedDate && styles.selectedDateText,
        ]}>
        {props.item.day + '\n' + '\n' + props.item.date}
      </Text>
    </TouchableOpacity>
  );

  const renderListItem = (props: any) => {
    return (
      <TouchableOpacity>
        <LinearGradinet
          colors={['#f3effe', '#ebe2fd', '#e6d8ff', '#e2d3fe', '#dbcaff']}
          start={{x: 0, y: 0.5}}
          end={{x: 1, y: 0.5}}
          style={styles.listitem}>
          <View style={styles.timebox}>
            <Ionicons
              style={{marginRight: 5}}
              name={'time-outline'}
              size={15}
              color={'#dbcaff'}
            />
            <Text style={styles.time}>{ dayjs(props.item.time).format('YYYY.MM.DD HH:mm') }</Text>
          </View>
          <View style={styles.textwrapper}>
            <View style={styles.textcontent}>
              <Text style={styles.listitemtext}>{props.item.title}</Text>
            </View>
            <TouchableOpacity onPress={() => checkHandle(props.index)}>
              {props.item.isFinish ? (
                <Ionicons name={'checkbox'} size={20} color={'#555c63'} />
              ) : (
                <Ionicons
                  name={'checkbox-outline'}
                  size={20}
                  color={'#9F96B3'}
                />
              )}
            </TouchableOpacity>
          </View>
        </LinearGradinet>
      </TouchableOpacity>
    );
  };

  const CustomEmptyComponent: React.FC = () => {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Image
          width={160}
          height={160}
          source={{
            uri: 'https://static-ftcms.jd.com/p/files/61a9e3183985005b3958672b.png',
          }}
        />
        <Text>暂无数据~</Text>
      </View>
    );
  };

  return (
    <GestureHandlerRootView>
      <View style={styles.wrapper}>
        <View style={styles.navbox}>
          {Navs.map((item, index) => {
            return (
              <LinearGradinet
                colors={['#7282f1', '#9391f6', '#a698f7']}
                key={index}
                style={[styles.navrightitem]}>
                <View style={styles.navinner}>
                  <View>
                    <Text style={styles.navrightitemtext}>{item.title}</Text>
                    <Text style={styles.navrightitemsmall}>{item.tip}</Text>
                  </View>
                  <View>
                    <Ionicons name={item.icon} size={30} color={'white'} />
                  </View>
                </View>
              </LinearGradinet>
            );
          })}
        </View>
      </View>
      <View style={styles.nowdatebox}>
        <Text style={styles.todonowdate}>
          {selectedDate && selectedDate.deteYearMonth}
        </Text>
        <Text style={styles.todocount}>共0个待办</Text>
      </View>
      <View style={styles.container}>
        <PanGestureHandler
          onGestureEvent={handleGestureEvent}
          onHandlerStateChange={handleGestureEnd}>
          <View style={styles.content}>
            <FlatList
              data={dateRange}
              renderItem={renderItem}
              keyExtractor={item => item.date}
              horizontal={true}
              showsHorizontalScrollIndicator={false}
              extraData={selectedDate}
            />
          </View>
        </PanGestureHandler>
      </View>
      <View style={styles.listwrapper}>
        <FlatList
          data={dataSource}
          renderItem={renderListItem}
          keyExtractor={item => String(item.id)}
          showsHorizontalScrollIndicator={false}
          ListEmptyComponent={CustomEmptyComponent}
        />
      </View>
    </GestureHandlerRootView>
  );
};

export default MyHome;
